package icom.acm.manager;

import icom.acm.bean.T_COLLEGE;
import icom.acm.util.DBConnect;
import java.sql.Statement;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

public class T_CollegeMgr {
	public int insert(final T_COLLEGE college){
		int flag = -1;
		String sql = "insert into T_COLLEGE(C_ID,C_NAME,C_TYPE,C_COUNTRY,C_CITY) " +
				"values(null, ?, ?, ?, ?)";
		DBConnect db = new DBConnect();
		db.setAutoCommit(false);
		db.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);		
		db.setString(1, college.getC_NAME());
		db.setString(2, college.getC_TYPE());
		db.setString(3, college.getC_COUNTRY());
		db.setString(4, college.getC_CITY());
		try {
			db.excute();
			flag = db.getGeneratedKeys();
			db.commit();
		} catch (MySQLIntegrityConstraintViolationException e) {
			// 数据重复
			flag = -1;
		} finally{
			db.setAutoCommit(true);
			db.close();
		}
		return flag;
	}
	
	public int update(final T_COLLEGE college){
		int flag = -1;
		String sql = "UPDATE T_COLLEGE SET C_NAME=?, C_TYPE=?," +
				" C_COUNTRY=?, C_CITY=? WHERE C_ID=?";
		DBConnect db = new DBConnect();
		db.setAutoCommit(false);
		db.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
		db.setString(1, college.getC_NAME());
		db.setString(2, college.getC_TYPE());
		db.setString(3, college.getC_COUNTRY());
		db.setString(4, college.getC_CITY());
		try {
			db.excute();
			flag = db.getGeneratedKeys();
			db.commit();
		} catch (MySQLIntegrityConstraintViolationException e) {
			// 数据重复
			flag = -1;
		} finally{
			db.setAutoCommit(true);
			db.close();
		}
		return flag;
	}
	public void delete(final int cid){
		final DBConnect db = new DBConnect();
		final String sql = "DELETE FROM T_COLLEGE WHERE C_ID = ?";
		System.out.println(sql);
		db.setAutoCommit(false);
		db.prepareStatement(sql);
		db.setInt(1, cid);
		try {
			db.excute();
			db.commit();
		} catch (final Exception ex) {
			ex.printStackTrace();
		} finally {
			db.setAutoCommit(true);
			db.close();
		}
	}
}
